package qdu.guisockets.serverlet;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class ClientHandler extends Thread{
    private Socket clienSocket;
    private ServerUI serverUI;
    public Socket getClientSocket() {
        return clienSocket;
    }
    private BufferedReader br;
    private BufferedWriter bw;
    public BufferedWriter getBw(){
        return bw;
    }
    public ClientHandler(Socket clienSocket, ServerUI serverUI){
        this.clienSocket = clienSocket;
        this.serverUI = serverUI;
        try{
            br = new BufferedReader(
                new InputStreamReader(clienSocket.getInputStream())
            );
            bw = new BufferedWriter(
                new OutputStreamWriter(clienSocket.getOutputStream())
            );
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public void updateMessage(String resultMessage) throws Exception{        
        serverUI.appendTf1Msg(resultMessage);
        TestSocketServer.updateOtherClients(resultMessage, ClientHandler.this);
    }
    public void run(){
        try {
            while(clienSocket!= null && !clienSocket.isClosed()){
                String message = br.readLine();
                if(message != null && !"".equals(message.trim())){
                    String resultMessage = "客户端:" + clienSocket.getInetAddress().toString()+":"+clienSocket.getPort() + "发来消息：\n" + message;
                    System.out.println(resultMessage);
                    updateMessage(resultMessage);
                }
                else if(message == null)
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(clienSocket != null){
                    updateMessage("客户端:" + clienSocket.getInetAddress().toString()+":"+clienSocket.getPort() + "离开");
                    clienSocket.close();
                    clienSocket = null;
                }
                if(br!=null)
                    br.close();                
                TestSocketServer.clientList.remove(ClientHandler.this);
            } catch (Exception e) {}
        }    
    }
}
